package com.um.swing.http;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.StreamProgress;
import cn.hutool.core.util.HashUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.um.swing.ThreadPool;
import com.um.swing.common.util.FileHashUtil;
import com.um.swing.dialog.JUpdateDialog;
import com.um.swing.http.bean.Version;
import com.um.swing.http.callback.HttpCallback;

import java.io.File;

/**
 * 名称：版本相关请求
 * 创建人：袁泉
 * 创建时间：2022年05月08日18:15:58
 */
public class HttpVersionApi extends HttpBaseApi {
    public static final String findNewVersionUrl = baseUrl + "/soft/version.json";
    private static HttpVersionApi __instance = null;

    public static HttpVersionApi getInstance() {
        if (__instance == null)
            __instance = new HttpVersionApi();
        return __instance;
    }

    public void findNewVersion(HttpCallback<Version> callback) {
        ThreadPool.execute(() -> {
            try {
                String s = get(findNewVersionUrl);
                JSONObject obj = JSONObject.parseObject(s);
                if ("ok".equals(obj.getString("state"))) {
                    Version data = obj.getObject("data", Version.class);
                    callback.onOk(data);
                } else {
                    callback.onFail(obj.getString("msg"));
                }
            } catch (Exception e) {
                e.printStackTrace();
                callback.onFail(e.getMessage());
            }
        });
    }

    //下载更新
    public void download(Version version, String targetPath, StreamProgress progress) {
        ThreadPool.execute(() -> {
            File file = new File(targetPath);
            boolean fileExists = false;
            if (file.exists()) {
                try {
                    progress.start();
                    String hash = FileHashUtil.hashFile(file);
                    if (hash.equals(version.getHash())) {
                        fileExists = true;
                        progress.finish();
                    } else {
                        //如果本地文件和服务器文件hash不一致，则重新下载
                        FileUtil.del(file);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (!file.getParentFile().exists()) {
                FileUtil.mkdir(file.getParentFile());
            }
            if (!fileExists) {
                HttpUtil.downloadFile(version.getDownloadUrl(), file, progress);
            }
        });
    }
}
